<?php
/**
 * @package qBase
 * @subpackage base
 */

/**
 * QErrorHandler
 * 
 * @package qBase
 * @subpackage base
 */
class QErrorHandler extends QObject 
{
	protected static $Delegates;
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public static function HandleError($errno, $errstr, $errfile, $errline, $shutdown = false)
	{
		// echo "{UUU}";
		
		if (($errno == E_NOTICE) || ($errno == E_USER_NOTICE))
		{
			self::debugData($errno, $errstr, $errfile, $errline);
			return ;
		}
		
		if (!$shutdown)
		{
			header("HTTP/1.1 500 Internal Server Error");
			// var_dump($errno, $errstr, $errfile, $errline);
			$ex = new Exception($errstr, $errno);
			throw $ex;
		}
		else 
		{
			header("HTTP/1.1 500 Internal Server Error");
			echo "<b>Fatal error: </b>$errstr<br/>
				<b>File:</b> $errfile<br/>
				<b>Line:</b> $errline<br/>";
		}
	}
	
	public static function AddDelegateOnShutdown(QDelegate $delegate)
	{
		if (!self::$Delegates)
			self::$Delegates = array();
		if (!isset(self::$Delegates["shutdown"]))
			self::$Delegates["shutdown"] = array();

		self::$Delegates["shutdown"][] = $delegate;
	}
	
	public static function OnShutdown()
	{
		if (self::$Delegates && isset(self::$Delegates["shutdown"]))
		{
			$ev = new QEvent("shutdown");
			foreach (self::$Delegates["shutdown"] as $delegate)
				$delegate->execute($ev);
		}
		
		$isError = false;
		
		$error = error_get_last();
		
		if ($error)
		{
			switch($error['type'])
			{
				case E_ERROR:
				case E_CORE_ERROR:
				case E_COMPILE_ERROR:
				case E_USER_ERROR:
				{
					$isError = true;
					break;
				}
				default:
				{
					break;
				}
			}
		}

        if ($isError)
        {
			QErrorHandler::HandleError($error["type"], $error["message"], $error["file"], $error["line"], true);
        }
	}
}

?>